package com.telecomyt.jwportal.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

/**
 * @author created by chengDa
 * @time 2020/10/13  10:29
 * @description
 */
public class HeadImageView extends View {
    private static final String TAG = "HeadImageView";
    /**
     * 要绘制的头像群组
     */
    private int width, height;
    private int count;
    /**
     * 1人情况字体大小
     */
    private float textSize = 20;
    /**
     * 字体颜色，默认白色
     */
    private int textColor;
    /**
     * 背景paint
     */
    private Paint mPaint;
    /**
     * 文字paint
     */
    private TextPaint textPaint;
    /**
     * 背景颜色
     */
    private int bgColor = 0xff419FE2;
    private String mImage;
    private String mName;
    public Bitmap bitmap;

    public HeadImageView(Context context) {
        this(context, null);
    }

    public HeadImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HeadImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    private void init() {

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeJoin(Paint.Join.ROUND);// 笔刷图形样式
        mPaint.setStrokeCap(Paint.Cap.ROUND);// 设置画笔转弯的连接风格
        mPaint.setDither(true);//防抖动
        textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setColor(Color.WHITE);//默认白色
        textPaint.setTextAlign(Paint.Align.LEFT);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        dealPic();
    }

    /**
     * @param size 单位：dp
     * @return
     */
    public HeadImageView setTextSize(float size) {
        this.textSize = size;
        return this;
    }


    /**
     * @param color 资源id，非颜色值
     * @return
     */
    public HeadImageView setTextColor(@ColorRes int color) {
        this.textColor = getResources().getColor(color);
        return this;
    }

    /**
     * @param color 资源id，非颜色值
     * @return
     */
    public HeadImageView setBgColor(@ColorRes int color) {
        this.bgColor = getResources().getColor(color);
        return this;
    }


    public void setHeadInfo(String image, String name) {
        invalidate();
        mImage = image;
        mName = name;
        if (width > 0 && height > 0) {
            dealPic();
        }
    }

    /**
     * 默认显示底色+文字，有头像则去加载，完成后绘制出来
     */
    public void dealPic() {
        dealPicWithIndex();
    }

    private void dealPicWithIndex() {
        if (!TextUtils.isEmpty(mImage)) {
            Glide.with(getContext())
                    .asBitmap()
                    .load(mImage)
                    .override(width, height)//宽高统一存为控件大小
                    .centerCrop()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            bitmap = resource;
                            postInvalidate();
                        }


                    });

        } else {
            recycleBitmap(bitmap);
            invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (TextUtils.isEmpty(mImage) && TextUtils.isEmpty(mName)) {
            return;
        }
        deal(canvas);
    }


    /**
     * @date: 2020/10/13
     * @author: chengDa
     * @description: 绘制一个人
     */
    private void deal(final Canvas canvas) {
        if (checkBitmap(bitmap)) {
            //新建Canvas层级
            int saveCount = canvas.saveLayer(0f, 0f, width, height, null, Canvas.ALL_SAVE_FLAG);
            //绘制底图——原来canvas上的内容dst
            canvas.drawBitmap(bitmap, 0, 0, mPaint);

            //生成圆形图片蒙版src
            Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvasMask = new Canvas(mask);
            RectF rf = new RectF(0f, 0f, width, height);
            canvasMask.drawOval(rf, mPaint);

            //设置交叉模式，绘制蒙版
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
            canvas.drawBitmap(mask, 0, 0, mPaint);

            //还原
            mPaint.setXfermode(null);
            //将如上画的层覆盖到原有层级上
            canvas.restoreToCount(saveCount);
        } else {
            mPaint.setColor(bgColor);
            canvas.drawCircle(width / 2f, height / 2f, width / 2f, mPaint);
            //画名字
            textPaint.setTextSize(sp2Px(textSize));
            String name = mName;
            name = name.length() > 2 ? name.substring(name.length() - 2, name.length()) : name;
            if (textColor != 0) {
                textPaint.setColor(textColor);
            }
            Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
            float baseline = height / 2f + (fontMetrics.bottom - fontMetrics.top) / 2f - fontMetrics.bottom;
            float x = (width - textPaint.measureText(name)) / 2f;
            canvas.drawText(name, x, baseline, textPaint);
        }
    }


    private float dp2Px(float dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    private float sp2Px(float sp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        recycleBitmap(bitmap);
    }

    private void recycleBitmap(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
    }

    private boolean checkBitmap(Bitmap bitmap) {
        if (bitmap == null || bitmap.isRecycled()) {
            return false;
        }
        return true;
    }
}